package cn.fr.util;

import org.apache.http.HttpHost;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.client.RestTemplate;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.HashMap;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 从队列中消费任务
 */
public class CustomerTaskFromQueue implements Runnable{
    private static Logger logger = LoggerFactory.getLogger("PROJECT_LOGGER");
    private final String taskUrl ;
    private RestTemplate restTemplate =new RestTemplate();


    private RestClientBuilder builder = RestClient.builder(new HttpHost("localhost", 9200, "http"));
    private RestHighLevelClient restHighLevelClient = new RestHighLevelClient(builder);

    public CustomerTaskFromQueue(String taskUrl) {
        this.taskUrl = taskUrl;
    }

    @Override
    public void run() {
        try {
            consum(taskUrl);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    private void consum(String taskUrl) throws Exception {
        logger.info("消费者线程已获取锁");
        transToEs(taskUrl);
    }

    /**
     * 根据文件url下载到本地
     * @param url
     * @throws IOException
     */
    public void savePicById(String url) throws IOException {
        logger.info("消费下载："+url);
        ResponseEntity<byte[]> response = restTemplate.exchange(
                url,
                HttpMethod.GET,
                null,
                byte[].class
        );
        byte[] fileData = response.getBody();
        FileOutputStream fos = new FileOutputStream(url.substring(40,48)+".png");
        fos.write(fileData);
        fos.close();
    }

    /**
     * 根据文件url转载到es中
     * @throws Exception
     */
    public void transToEs(String url) throws Exception{
        ResponseEntity<byte[]> response = restTemplate.exchange(
                url,
                HttpMethod.GET,
                null,
                byte[].class
        );
        // 将图片转换为字节数据
        byte[] imgData = response.getBody();
        // 将字节数据转换为Base64字符串
        String base64Image = Base64.getEncoder().encodeToString(imgData);
        // 创建索引请求
        IndexRequest request = new IndexRequest("imgstore"); // 你的索引名
        request.id(System.currentTimeMillis()+"_"+url.substring(40,48)); // 文档ID
        request.source("blob", base64Image);
//        request.source("name", System.currentTimeMillis()+"", XContentType.JSON);
        // 发送请求并获取响应
        IndexResponse response1 = restHighLevelClient.index(request, RequestOptions.DEFAULT);
        // 输出结果
        System.out.println("Index response status: " + response1.getResult());
    }
}
